package com.ruoyi.activiti.service.impl;

import com.github.pagehelper.Page;
import com.ruoyi.activiti.domain.BizInterviewEvaluationInfoVo;
import com.ruoyi.activiti.mapper.BizInterviewEvaluationInfoMapper;
import com.ruoyi.activiti.service.IBizInterviewEvaluationInfoService;
import com.ruoyi.activiti.service.IProcessService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 面试评价Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-03-23
 */
@Service
public class BizInterviewEvaluationInfoServiceImpl implements IBizInterviewEvaluationInfoService {
    @Autowired
    private BizInterviewEvaluationInfoMapper bizInterviewEvaluationInfoMapper;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private IProcessService processService;

    /**
     * 查询面试评价
     * 
     * @param id 面试评价ID
     * @return 面试评价
     */
    @Override
    public BizInterviewEvaluationInfoVo selectBizInterviewEvaluationInfoById(Long id)
    {   BizInterviewEvaluationInfoVo  vo=bizInterviewEvaluationInfoMapper.selectBizInterviewEvaluationInfoById(id);
        SysUser sysUser = userMapper.selectUserByLoginName(vo.getApplyUser());
        if (sysUser != null) {
            vo.setApplyUserName(sysUser.getUserName());
        }
        return vo;
    }

    /**
     * 查询面试评价列表
     * 
     * @param bizInterviewEvaluationInfo 面试评价
     * @return 面试评价
     */
    @Override
    public List<BizInterviewEvaluationInfoVo> selectBizInterviewEvaluationInfoList(BizInterviewEvaluationInfoVo bizInterviewEvaluationInfo)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        // PageHelper 仅对第一个 List 分页
        Page<BizInterviewEvaluationInfoVo> list = (Page<BizInterviewEvaluationInfoVo>) bizInterviewEvaluationInfoMapper.selectBizInterviewEvaluationInfoList(bizInterviewEvaluationInfo);
        Page<BizInterviewEvaluationInfoVo> returnList = new Page<>();
        for (BizInterviewEvaluationInfoVo leave: list) {
            SysUser sysUser = userMapper.selectUserByLoginName(leave.getCreateBy());
            if (sysUser != null) {
                leave.setCreateUserName(sysUser.getUserName());
            }
            SysUser sysUser2 = userMapper.selectUserByLoginName(leave.getApplyUser());
            if (sysUser2 != null) {
                leave.setApplyUserName(sysUser2.getUserName());
            }
            // 当前环节
            if (StringUtils.isNotBlank(leave.getInstanceId())) {
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(leave.getInstanceId())
//                        .singleResult();
                        .list();    // 例如请假会签，会同时拥有多个任务
                if (!CollectionUtils.isEmpty(taskList)) {
                    TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
                    leave.setTaskId(task.getId());
                    if (task.getSuspensionState() == 2) {
                        leave.setTaskName("已挂起");
                        leave.setSuspendState("2");
                    } else {
                        leave.setTaskName(task.getName());
                        leave.setSuspendState("1");
                    }
                } else {
                    // 已办结或者已撤销
                    leave.setTaskName("已结束");
                }
            } else {
                leave.setTaskName("未启动");
            }
            returnList.add(leave);
        }
        returnList.setTotal(CollectionUtils.isEmpty(list) ? 0 : list.getTotal());
        returnList.setPageNum(pageNum);
        returnList.setPageSize(pageSize);
        return returnList;
    }

    /**
     * 新增面试评价
     * 
     * @param bizInterviewEvaluationInfo 面试评价
     * @return 结果
     */
    @Override
    public int insertBizInterviewEvaluationInfo(BizInterviewEvaluationInfoVo bizInterviewEvaluationInfo)
    {   bizInterviewEvaluationInfo.setCreateBy(ShiroUtils.getLoginName());
        bizInterviewEvaluationInfo.setCreateTime(DateUtils.getNowDate());
        return bizInterviewEvaluationInfoMapper.insertBizInterviewEvaluationInfo(bizInterviewEvaluationInfo);
    }

    /**
     * 修改面试评价
     * 
     * @param bizInterviewEvaluationInfo 面试评价
     * @return 结果
     */
    @Override
    public int updateBizInterviewEvaluationInfo(BizInterviewEvaluationInfoVo bizInterviewEvaluationInfo)
    {
        bizInterviewEvaluationInfo.setUpdateTime(DateUtils.getNowDate());
        return bizInterviewEvaluationInfoMapper.updateBizInterviewEvaluationInfo(bizInterviewEvaluationInfo);
    }

    /**
     * 删除面试评价对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBizInterviewEvaluationInfoByIds(String ids)
    {
        return bizInterviewEvaluationInfoMapper.deleteBizInterviewEvaluationInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除面试评价信息
     * 
     * @param id 面试评价ID
     * @return 结果
     */
    @Override
    public int deleteBizInterviewEvaluationInfoById(Long id)
    {
        return bizInterviewEvaluationInfoMapper.deleteBizInterviewEvaluationInfoById(id);
    }



    /**
     * 启动流程
     * @param entity
     * @param applyUserId
     * @return
     */
    @Override
    public ProcessInstance submitApply(BizInterviewEvaluationInfoVo entity, String applyUserId, String key, Map<String, Object> variables) {
        entity.setApplyUser(applyUserId);
        entity.setApplyTime(DateUtils.getNowDate());
        entity.setUpdateBy(applyUserId);
        bizInterviewEvaluationInfoMapper.updateBizInterviewEvaluationInfo(entity);
        String businessKey = entity.getId().toString(); // 实体类 ID，作为流程的业务 key

        ProcessInstance processInstance = processService.submitApply(applyUserId, businessKey, entity.getInterviewerName(), entity.getInterviewTime(), key, variables);
        String processInstanceId = processInstance.getId();
        entity.setInstanceId(processInstanceId); // 建立双向关系
        bizInterviewEvaluationInfoMapper.updateBizInterviewEvaluationInfo(entity);
        return processInstance;

    }

    /**
     * 查询待办任务
     */
    public Page<BizInterviewEvaluationInfoVo> findTodoTasks(BizInterviewEvaluationInfoVo leave, String userId) {
        // 手动分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        Page<BizInterviewEvaluationInfoVo> list = new Page<>();

        List<BizInterviewEvaluationInfoVo> results = new ArrayList<>();
        List<Task> tasks = processService.findTodoTasks(userId, "interview");
        // 根据流程的业务ID查询实体并关联
        for (Task task : tasks) {
            TaskEntityImpl taskImpl = (TaskEntityImpl) task;
            String processInstanceId = taskImpl.getProcessInstanceId();
            // 条件过滤 1
            if (StringUtils.isNotBlank(leave.getInstanceId()) && !leave.getInstanceId().equals(processInstanceId)) {
                continue;
            }
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            BizInterviewEvaluationInfoVo leave2 =  bizInterviewEvaluationInfoMapper.selectBizInterviewEvaluationInfoById(new Long(businessKey));
            leave2.setTaskId(taskImpl.getId());
            if (taskImpl.getSuspensionState() == 2) {
                leave2.setTaskName("已挂起");
            } else {
                leave2.setTaskName(taskImpl.getName());
            }
            SysUser sysUser = userMapper.selectUserByLoginName(leave2.getApplyUser());
            leave2.setApplyUserName(sysUser.getUserName());
            results.add(leave2);
        }

        List<BizInterviewEvaluationInfoVo> tempList;
        if (pageNum != null && pageSize != null) {
            int maxRow = (pageNum - 1) * pageSize + pageSize > results.size() ? results.size() : (pageNum - 1) * pageSize + pageSize;
            tempList = results.subList((pageNum - 1) * pageSize, maxRow);
            list.setTotal(results.size());
            list.setPageNum(pageNum);
            list.setPageSize(pageSize);
        } else {
            tempList = results;
        }

        list.addAll(tempList);

        return list;
    }

    /**
     * 查询已办列表
     * @param bizLeave
     * @param userId
     * @return
     */
    @Override
    public Page<BizInterviewEvaluationInfoVo> findDoneTasks(BizInterviewEvaluationInfoVo bizLeave, String userId) {
        // 手动分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        Page<BizInterviewEvaluationInfoVo> list = new Page<>();

        List<BizInterviewEvaluationInfoVo> results = new ArrayList<>();
        List<HistoricTaskInstance> hisList = processService.findDoneTasks(userId, "interview");
        // 根据流程的业务ID查询实体并关联
        for (HistoricTaskInstance instance : hisList) {
            String processInstanceId = instance.getProcessInstanceId();
            // 条件过滤 1
            if (StringUtils.isNotBlank(bizLeave.getInstanceId()) && !bizLeave.getInstanceId().equals(processInstanceId)) {
                continue;
            }
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            BizInterviewEvaluationInfoVo leave2 = bizInterviewEvaluationInfoMapper.selectBizInterviewEvaluationInfoById(new Long(businessKey));
            BizInterviewEvaluationInfoVo newLeave = new BizInterviewEvaluationInfoVo();
            BeanUtils.copyProperties(leave2, newLeave);
            newLeave.setTaskId(instance.getId());
            newLeave.setTaskName(instance.getName());
            newLeave.setDoneTime(instance.getEndTime());
            SysUser sysUser = userMapper.selectUserByLoginName(leave2.getApplyUser());
            newLeave.setApplyUserName(sysUser.getUserName());
            results.add(newLeave);
        }

        List<BizInterviewEvaluationInfoVo> tempList;
        if (pageNum != null && pageSize != null) {
            int maxRow = (pageNum - 1) * pageSize + pageSize > results.size() ? results.size() : (pageNum - 1) * pageSize + pageSize;
            tempList = results.subList((pageNum - 1) * pageSize, maxRow);
            list.setTotal(results.size());
            list.setPageNum(pageNum);
            list.setPageSize(pageSize);
        } else {
            tempList = results;
        }

        list.addAll(tempList);

        return list;
    }

}
